<?php 	
/**
 * 任务系统
 */  
class task {
	public function getIndex($param){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $uid = Session::$user['uid'];
	    $tId=$param->tId;
	    if(!$param->qId){
	    	$param->qId=self::getQuanId($param);
	    }
	    if(!$param->tId){
	    	$param->tId=self::getDefaulttId($param);
	    }
	    $result=self::getTaskConfig($param);
	    $param->miUId=$uid;
	    $taskState=self::checkTaskStatus($param,$result);
	    $json=$result["json"];
	    if($json->REWARD->KEY=="GIFT" && $taskState > 1) {
	    	$result["prodetail"]=self::getProductDetail($json);
	    }
	    $result["taskState"]=$taskState;
	    $result["tId"]=$param->tId;
	    $result["qId"]=$param->qId;  
	    Output::instance()->module('task',"index")->object($result);
	}
	/**
	 * [getQuanId 获取默认的圈]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	private function getQuanId($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$MiQuanUserModel=M("quan_user");
		Session::switchCustomer($customerId);
	    $uid = Session::$user['uid'];
	    $qId=$param->qId;
		if(!$qId) {
	    	$quanList=$MiQuanUserModel->where("uid=$uid")->find();
	    	if($quanList) {
	    		$qId=$quanList["qid"];
	    	}
	    }
	    return $qId;
	}
	/**
	 * [getDefaulttId 获取默认的任务id]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	private function getDefaulttId($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$MiTaskModel=M("mitask");
		Session::switchCustomer($customerId);
	    $task=$MiTaskModel->where("isDefault=1")->find();
	    if($task) {
    		$tId=$task["id"];
    	}
	    return $tId;
	}
	private function getProductDetail($json){
	    if(!$json) {
	    	return;
	    }
	    $pid=$json->REWARD->GIFT->PID;
	    if(!$pid) {
	    	return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $ProductModel = M("module_product");
	    $specModel = M("module_product_specification"); 
	    Session::switchCustomer($customerId);
	    $mplwhere["pro.id"]=$pid;
	    $mplwhere["pro.isRemoved"]=0;
	    $mplwhere["pro.deleted"]=0;
	    $productInfo= $ProductModel->alias('pro')
	    ->field('pro.name,pro.id,pro.picUrl,pro.fixedPrice,
	    	pro.discountedPrice,pro.fromCustomerId,pro.supportSpecification,
	    	pro.inventory,pro.inventoryCount')
	    ->where($mplwhere)
	    ->find();

	    if($productInfo) {
	    	if ($productInfo["supportSpecification"] == 1) {
	            $arrFirstSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	            ->order("sepc.id")
	            ->getField("specificationName", true);
	        
	            if ($arrFirstSpec) {
	                $productInfo["sizeUnit"] = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	                ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	                ->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
	                ->getField("groupName");
	        
	            }
	            if($arrFirstSpec){
					$productInfo["size"] = json_encode($arrFirstSpec);
	            }

	            $arrSecSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	            ->getField("specificationName", true);
	        
	            if ($arrSecSpec) {
	                $productInfo["colorUnit"] = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	                ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	                ->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
	                ->getField("groupName");
	            }
	            if($arrSecSpec) {
	            	$productInfo["color"] = json_encode($arrSecSpec);
	            }
	            if ($productInfo["inventory"] == 1) {
	            	if (isset($arr['availSku'])) {
	                    $availSku=$arr['availSku'];
	                }else{
	                    $params["pid"] = $productInfo['id'];
	                    $params["arrFirstSpec"] = $arrFirstSpec;
	                    $params["arrSecSpec"] = $arrSecSpec;
	                    $availSku = Module::callModule('product', NULL, 'getProductInventory', $params);
	                }
	                $val["availSku"] = json_encode($availSku);
	            }
				if (!isset($val["availSku"])) {
					$val["availSku"] = json_encode(null);
				}
	        }
	    }
	    $prodetail=json_encode($productInfo);
	    return $prodetail;
	}
	public function getTaskList($param) {
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $uid = Session::$user['uid'];
	    $result["qId"]=$param->qId;   
	    Output::instance()->module('task',"list")->object($result);
	}
	/**
	 * [getTaskConfig 获取任务配置]
	 * @return [type] [description]
	 */
	public function getTaskConfig($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
		$userName=Session::$user['userName'];
		$tId=$param->tId;
		$uid = Session::$user['uid'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $taskModel=M("mitask");
	    $taskUserModel=M("mitask_user");
	    Session::switchCustomer($customerId);
	    $where["a.deleted"]=array('eq',0);
	    $where["a.status"]=array('eq',1);
	    $where["a.id"]=array('eq',$tId);
	    $curtime= strtotime(date('Y-m-d H:i:s'));
	    $result=$taskModel->alias("a")
	    ->field("a.*,a.id as tId")
	    ->where($where)
	    ->find();
	    if($result){

			$userList=$taskUserModel->where("tId=$tId")->select();
			$curUserList=$taskUserModel->where("tId=$tId and uId=$uid")->find();
		
	        $json=json_decode($result["jsonStr"]);
	        $json1=json_decode($result["jsonStr"],true);
	    	$result["json"]=$json;
	    	$result["json1"]=$json1;
	    	$startTime=strtotime($result["startTime"]);
	    	$endTime=strtotime($result["endTime"]);
	    	$result["taskStatus"]="0";
	    	if($result["maxNum"]) {
	    		if(!$curUserList || count($curUserList) < 1) {
	    			if($userList && count($userList) >=$result["maxNum"]) {
			        	$result["code"]=4;
			    		$result["msg"]="已抢完";
			    		return $result;
			        }
	    		}
			}
			if($startTime > $curtime){
	    		$result["code"]=3;
	    		$result["msg"]="未开始";
	    		return $result;
	    	}
			if($endTime < $curtime){
	    		$result["code"]=5;
	    		$result["msg"]="已结束";
	    		return $result;
	    	}
	    } else {
	    	$result["code"]=6;
	    	$result["msg"]="不存在";
	    	return $result;
	    }
	    $result["code"]=0;
	    $this->taskConfig=$result;
	    return $result;
	}
	/**领取任务*/
	public function getTask($param){
		$uid = Session::$user['uid'];
	    $customerId = Session::$user['customerId'];
	    $taskConfig=self::getTaskConfig($param);
		$json=$this->taskConfig["json"];
		Session::switchCustomer(0);
		//判断任务启动条件是否满足
		$front=$json->FRONT;
		$main=$json->MAIN;
		$out=new stdClass();
		$qId=$param->qId;
		$regParam=new stdClass();
		$regParam->qId=$qId;
		$regParam->tId=$taskConfig["id"];
		$regParam=urlencode(json_encode($regParam));
		$regUrl=C("SERVER_HOST") . "call.html?customerId=$customerId&module=quan&method=mireg&scope=1&params=".$regParam;
		$param->regUrl=$regUrl;
		if($taskConfig["code"]!=4) {
			foreach ($front as $key => $value) {
				switch ($key) {
					case 'REG': //是否已经注册
						$UserModel=M("all_user");
						$userRs=$UserModel->where("id=$uid and phone=''")->find();
						if($userRs && count($userRs) > 0) {
							$out->code=1;
							$out->msg="您还未注册，不能领取任务，现在去注册？";
							$out->url=$regUrl; //去注册
						}
						break;
					default:
						break;
				}
			}
			if(!$out->code) {
				$success=self::addTaskforUser($param);
				if($success) {
					$out=self::getTaskMainUrl($param,$taskConfig);
				} else {
					$out->code=1;
					$out->msg="任务领取失败！";
				}
			}
		} else {
			$out->code=1;
			$out->msg=$taskConfig["msg"];
		}
	    Session::switchCustomer($customerId);
	    Output::instance()->object($out);
	}
	/**
	 * [addTaskforUser 给用户添加任务]
	 * @param [type] $param [description]
	 */
	public function addTaskforUser($param) {
		$uid = Session::$user['uid'];
	    $customerId = Session::$user['customerId'];
	    $tId=$param->tId;
	    $qId=$param->qId;
		Session::switchCustomer(0);
		$miTaskUser=M("mitask_user");
	    Session::switchCustomer($customerId);
	    $where["tId"]=array('eq',$tId);
	    $where["uId"]=array('eq',$uid);
	    $taskUser=$miTaskUser->where($where)->find();
	    if(!$taskUser || count($taskUser) < 1) { //不在任务列表中
		    $addData=array(
		    	"qId"=>$qId,
		    	"uId"=>$uid,
		    	"tId"=>$tId,
		    	"reward"=>"",
		    	"status"=>"1",
		    	"rate"=>"",
		    	"issend"=>0,
		    	"createTime"=>date("Y-m-d H:i:s")
		    );
		    $success=$miTaskUser->add($addData);
		    return $success;
		} else {
			return $taskUser["id"];
		}
	}
	public function getTaskMainUrl($param,$taskConfig){
		$uid = Session::$user['uid'];
	    $customerId = Session::$user['customerId'];
	    $qId=$param->qId;
		$json=$taskConfig["json"];
		Session::switchCustomer(0);			
		$main=$json->MAIN;
		$out=new stdClass();
		$key=$main->KEY;
		switch ($key) {
			case 'REG': //是否已经注册
				$out->code=0;
				$out->url=$param->regUrl;
				break;
			case 'SHARE':
				$sId=$json->SID;
				$shareModel=M("mishare");
				$share=$shareModel->where("id=$sId")->find();	
				if($share) {
					$p=new StdClass();
					$p->miUId=$uid;
					$p->qId=$qId;
					$p->id=$share["moduleId"];
					$p->sId=$sId;
					$p->toGuide=1;
					$p->tId=$taskConfig["tId"];
					$detail=Module::callModule($share["module"], Session::$user,"getObjectDetail", $p);
					$out->code=0;
					$out->url=$detail["detailUrl"];
				}
				break;
		}
	    Session::switchCustomer($customerId);
	    return $out;
	}
	/**
	 * [updateTaskComplete 更新任务状态为已经完成]
	 * @param  [type] $tId [description]
	 * @return [type]      [description]
	 */
	public function updateTaskComplete($param) {
		$customerId = Session::$user['customerId'];
		$platCustomerId = C('PLANT_CUSTOMERID');
		Session::switchCustomer(0);
		$miTaskModel=M("mitask_user");
		$miUserModel=M("all_user");
	    Session::switchCustomer($customerId);
	    $data["status"]="2";
	    $data["issend"]="1";
	    $data["completeTime"]=date("Y-m-d H:i:s");
	    $tId=$param->tId;
	    $uid=$param->miUId;
	    $qId=$param->qId;
	    $where["tId"]=array('eq',$tId);
	    $where["uId"]=array('eq',$uid);
	    $taskUser=$miTaskModel->where($where)->find();
	    if(!$taskUser || count($taskUser) < 1) { //任务已经完成，但是之前没有领取任务
	    	//自动添加任务
	    	$p=new stdClass();
	    	$p->tId=$param->tId;
	    	$p->qId=$param->qId;
	    	self::addTaskforUser($p);
	    }
	    $taskUser=$miTaskModel->alias("a")
	    ->join("inner join wx_mitask b on a.tId=b.id")
	    ->field("a.*,b.name,b.jsonStr")
	    ->where($where)->find();
	    
	    if($taskUser && $taskUser["issend"]==0) {
	    	$success=$miTaskModel->where($where)->save($data);
	    	if($success!==false) {
		    	//发送模板消息通知任务完成
		    	Log::write("发送消息通知");
		    	$weixinUser=$miUserModel->alias("a")
	    		->join("inner join wx_".$platCustomerId."_user_weixin_info b on a.weixinUserId=b.id")
	    		->where("a.id=$uid")->find();
	    		if($weixinUser) {
	    			self::SendCheckNotice($qId,$weixinUser["openid"],$taskUser);	
	    		}
		    	$taskUser=$miTaskModel->where($where)->find(); 
		    	return $taskUser;
		    }
	    } else {
	    	$taskUser=$miTaskModel->where($where)->find(); 
		    return $taskUser;
	    }
	}
	/**
	 * [SendAuthNotice 发送任务完成通知]
	 * @param [type] $ids      [description]
	 * @param [type] $userName [description]
	 */
	public static function SendCheckNotice($qId,$toUser,$taskUser){
		$platCustomerId=C("PLANT_CUSTOMERID");
		Session::switchCustomer($customerId);
		$TemplateModel = new Model();
		$sql = "SELECT * from wx_".$platCustomerId."_template_messages where status = 'mitaskover' limit 1";
		$templatemsg = $TemplateModel->query($sql);
		$tId=$taskUser["tId"];
		if (count($templatemsg)>0) {
			$templateId = $templatemsg[0]['templateId'];
		}
		$jsonStr = json_decode($taskUser['jsonStr']);
		Log::write("任务成功通知");
		if($templatemsg) {
			$data['first'] = array('value'=> $jsonStr->TEMPLETE->TASKOVER_FIRST,'color'=>"#743A3A");
			$data['keyword1'] = array('value'=> $taskUser["name"],'color'=>"#743A3A");
			$data['keyword2'] = array('value'=> $jsonStr->TEMPLETE->TASKOVER_SECOND,'color'=>"#743A3A");
			$data['remark'] = array('value'=> $jsonStr->TEMPLETE->TASKOVER_REMARK,"color"=>'#008000');
			$url = C("SERVER_HOST") . "call.html?customerId=" . $platCustomerId .
			"&module=task&method=index&params=%7B%22qId%22%3A%22$qId%22%2C%22tId%22%3A%22$tId%22%7D";
		 	$url = urlencode($url);
			$topcolor = "#FF0000";
			//data得转json
			$apiresult=WeixinApi::sendTpl($toUser, $templateId,$url,$topcolor,$data);
		}
	}
	/**
	 * [checkTaskStatus 检查任务达成状态]
	 * @param  [type] $param      [description]
	 * @param  [type] $taskConfig [description]
	 * @return [type]             [description]
	 */
	public function checkTaskStatus($param,$task){
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miTaskModel=M("mitask_user");
		$userModel=M("all_user");
		$miShareStatModel=M("mishare_stat");
	    Session::switchCustomer($customerId);
	    $uid=$param->miUId;
	    $qId=$param->qId;
	    $json=json_decode($task["jsonStr"],true);
		$main=$json["MAIN"];
		$target=$json["TARGET"];
		$key=$target["KEY"];
		$tId=$task["tId"];
		$param->tId=$tId;
		$taskUser=$miTaskModel->where("uid=$uid and tId=$tId")->find();
		switch ($key) {
			case 'REG':
				$result=$userModel->where("id=$uid")->find();
				if(!$taskUser) {
					$out["status"]=0;
				} else {
					$out["status"]=1;
					if($result["phone"]!="") {
						return self::updateTaskComplete($param);
					}
				}
				break;
			case 'UV':
				$sId=$json["SID"];
				$resCount=$miShareStatModel->where("miUid=$uid and sId=$sId")->find();
				$tar=$json["TARGET"]["UV"];
				$uv=0;
				if($resCount) {
					$uv=$resCount["uv"];
				}
				if($taskUser) {
					$addData["rate"]=$uv."/".$tar;
					$out["count"]=$uv;
					$out["min"]=$tar;
					$out["per"]=($uv/$tar)*100;
					$out["status"]=1;
					$miTaskModel->where("uid=$uid and tId=$tId")->save($addData);
					if($uv>=$tar) {
						return self::updateTaskComplete($param);
					}	
				} else {
					$out["status"]=0;
				}
				break;
			default:
				break;
		}
		//检查前置条件
		return $out;
	}
	public function updateTaskStatus($param) {
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miTaskModel=M("mitask_user");
	    Session::switchCustomer($customerId);
	    $uid=$param->miUId;
	    $qId=$param->qId;
	    Log::write("进入触发任务检查");
	    if($uid) {
	    	$userTaskList=$miTaskModel->alias("a")
	    	->join("wx_mitask b on a.tId=b.id")
	    	->field("a.*,b.jsonStr")
	    	->where("a.uId=$uid and b.deleted=0 and a.status <> 3")->select();
	    	if($userTaskList) {
	    		foreach ($userTaskList as $task) { //遍历任务
	    			Log::write("进入触发任务检查循环任务内");
    				self::checkTaskStatus($param,$task);
	    		}
	    	}
	    }
	}
	function randomFloat($min = 0, $max = 1) { 
		$num=$min + mt_rand() / mt_getrandmax() * ($max - $min); 
		return round($num,2); 
	}
	/**
	 * [getReward 获取任务奖励]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function getReward($param){
		$uid = Session::$user['uid'];
		$qId=$param->qId;
		$tId=$param->tId;
		$userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miTaskUser=M("mitask_user");
		$miShareStat=M("mishare_stat");
		$miAccountModel=M("miaccount_friend");
	    Session::switchCustomer($customerId);
	    $where["a.uid"]=array("eq",$uid);
	    $where["a.tId"]=array("eq",$tId);
	    $where["a.qId"]=array("eq",$qId);
	    //判断任务是否已经完成
		$taskUserResult=$miTaskUser->alias("a")
		->join("inner join wx_mitask b on a.tId=b.id")
		->field("a.*,b.jsonStr,b.name")
		->where($where)->find();
		if(!$taskUserResult) {
			$out->code=0;
			$out->msg="领取的任务不存在！";
			return;
		}
		if($taskUserResult && $taskUserResult["status"]==2 && !$taskUserResult["rewardType"]) {
			$json=json_decode($taskUserResult["jsonStr"]);
			$reward=$json->REWARD;
			$id=$taskUserResult["id"];

			foreach ($reward as $key => $value) {
				switch($key) { //红包奖励
					case "REDENVE":
					case "ACCOUNT":
						$isRand=$value->RANDOM;
						$num=$value->NUM;
						$wishText=$value->WISHTEXT;
						if(!$wishText) {
							$wishText="终于等到你！";
						}
						if($isRand==1) {
							if($value->RANDMIN!=="" && $value->RANDMAX) {
								$num=self::randomFloat($value->RANDMIN,$value->RANDMAX);
							}
						}
						if($key=="REDENVE") {
							$time=(int)date("H");
							if($time >=0 && $time <8){
								$out->code=1;
					   	    	$out->msg="亲，0点-8点是红包侠休息时间，请过后再来哦!";
					   	    	Output::instance()->object($out); 
					   	    	return;
							}
							$success=WeixinApi::sendRedEnvelopeByOpenId(
					   	  		"密友圈",
					   	  		$userName,
					   	  		$num,
					   	  		$wishText,
					   	  		false
					   	    );
					   	    Log::write("红包返回结果".$success);
						} 
						if($key=="ACCOUNT"){
							//账户充值
							$miAccountModel->startTrans();
							$success1=$miAccountModel->query("update wx_quan_user set miCoins=miCoins+".$num." where uid=$uid and qid=$qId");
							$addData=array(
								"module"=>"task",
								"moduleId"=>"0",
								"uId"=>$uid,
								"quanId"=>$qId,
								"vId"=>0,
								"description"=>$taskUserResult["name"],
								"sId"=>0,
								"vsistId"=>0,
								"money"=>$num,
								"type"=>0,
								"createTime"=>date("Y-m-d H:i:s"),
								"deleted"=>0
							);
							$success2=$miAccountModel->add($addData);
							if($success1!==false && $success2!==false) {
								$success=1;
								$miAccountModel->commit();
							} else {
								$success=0;
								$miAccountModel->rollback();
							}
						}
						if($success) {
				   	    	$upData["reward"]=$num;
				   	    	$upData["rewardType"]=$key;
				   	    	$upData["completeTime"]=date("Y-m-d H:i:s");
				   	    	$upData["status"]=3;
				   	    	$result=$miTaskUser->where("id=$id")->save($upData);
				   	    	if($result) {
				   	    		$out->code=0;
				   	    		$out->msg="领取成功！";
				   	    	}
				   	    } else {
				   	    	$out->code=1;
				   	    	$out->msg="系统繁忙，请稍后再试！";
				   	    }
					break;
				}
			}
		}
		Output::instance()->object($out); 
	}
	/**
	 * [getReward 获取礼物任务奖励]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function getRewardGift($param){
		$uid = Session::$user['uid'];
		$qId=$param->qId;
		$tId=$param->tId;
		$oid=$param->oid;
		$userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miTaskUser=M("mitask_user");
		$ProductOrderModel=M("module_product_order");
	    Session::switchCustomer($customerId);
	    $where["a.uid"]=array("eq",$uid);
	    $where["a.tId"]=array("eq",$tId);
	    $where["a.qId"]=array("eq",$qId);
	    //判断任务是否已经完成
		$taskUserResult=$miTaskUser->alias("a")
		->join("inner join wx_mitask b on a.tId=b.id")
		->field("a.*,b.jsonStr,b.name")
		->where($where)->find();

		$order=$ProductOrderModel->alias("a")
		->join("inner join wx_module_product_order_detail b on a.id=b.oid")
		->where("a.id=$oid")->find();

		if(floatval($order["count"]) >1 ) {
			$out=new stdClass();
			$out->code=1;
			$out->msg="任务奖励商品，只能允许购买一个";
			Output::instance()->object($out);
			return;
		}
		if($taskUserResult && $taskUserResult["status"]==2 && !$taskUserResult["rewardType"]) {
			$order=$ProductOrderModel->where("id=$oid")->find();
			$id=$taskUserResult["id"];
			if($order) {
				$ProductOrderModel->startTrans();
				$updateData=array(
					"miUid"=>"0",
					"price"=>"0",
					"logisticsCost"=>0
				);
				$orderSuccess=$ProductOrderModel->where("id=$oid")->save($updateData); //更新订单价格
				$upTaskData["reward"]=$oid;
	   	    	$upTaskData["rewardType"]="GIFT";
	   	    	$upTaskData["completeTime"]=date("Y-m-d H:i:s");
	   	    	$upTaskData["status"]=3;
	   	    	$updateTaskStatus=$miTaskUser->where("id=$id")->save($upTaskData);
	   	    	if($orderSuccess!=false && $updateTaskStatus!=false) {
	   	    		$ProductOrderModel->commit();
	   	    		$out->code=0;
	   	    	} else {
	   	    		$out->code=1;
				   	$out->msg="系统繁忙，请稍后再试！";
	   	    	}
			}
		}
		Output::instance()->object($out); 
	}
	/**
	 * [gettastList 获取任务列表]
	 * @param  [type]  $param [qid]
	 * @param  integer $start [偏移量]
	 * @param  integer $limit [截取数]
	 * @return [type]         [description]
	 */
	public function gettaskListData($param,$start=0,$limit=10){
		$uid = Session::$user['uid'];
		$qId=$param->qId;
	    $customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miTaskModel= M("mitask");
		$miTaskUserModel = M("mitask_user");
	    Session::switchCustomer($customerId);
		$where['task.deleted'] = 0;
		$where['task.status'] = 1;
		$time = date("Y-m-d H:i:s");
		$where['task.startTime'] = array('elt', $time);
		$where['task.endTime'] = array('egt', $time);
		$where['_string']="FIND_IN_SET('$qId', qids)";
	    $pageStart=$start * $limit;
 		$arr = $miTaskModel->alias('task')
	    		->where($where)
	    		->field('task.id as taskid,task.name,task.description,task.rewardDescription,task.startTime,task.endTime,task.jsonStr')
	    		->limit($pageStart,$limit)
	    		->select();
	   	foreach ($arr as $key => $value) {
	    	$json=json_decode($value["jsonStr"]);
	    	$reward=$json->REWARD;
	    	$uwhere['tId'] = $value['taskid'];
	    	$uwhere['uId'] = $uid;
	    	$data= $miTaskUserModel->where($uwhere)->find();
	    	$arr[$key]['ustatus'] = $data['status'];
	    	$arr[$key]['rate'] = $data['rate'];
	    	$arr[$key]['reward']=$reward;
	    	$rate=$data['rate'];
	    	$rateArr=explode('/', $rate);
	    	if(count($rateArr) > 1 ) {
	    		$min=$rateArr[0];
	    		$max=$rateArr[1];
	    		$per=($min/$max)*100;
	    		$arr[$key]['per']=$per;
	    	}
	    }
	    $count =$miTaskModel->alias('task')
		->where($where)
		->field('task.id as taskid,task.name,task.description,task.rewardDescription,task.startTime,task.endTime,task.jsonStr')
		->limit($pageStart,$limit)
		->count();
	    $out=new StdClass();
		$out->count=$count;
		$out->pageCount=getPageCount($count,$limit);
		$out->list=$arr;
		if($arr){
			Output::instance()->object($out);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}	

	}
}